package com.itheima.service.serviceImpl;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.domain.dto.LonginDto;
import com.itheima.domain.pojo.Emp;
import com.itheima.domain.vo.LoginVo;
import com.itheima.mapper.EmpMapper;
import com.itheima.service.LoginService;
import com.itheima.utils.JWTkey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-08-31 16:58
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginVo login(LonginDto loginDto) throws ClientException {
        if (Objects.equals(loginDto.getUsername(), "")||Objects.isNull(loginDto.getUsername())){
            throw new ClientException("用户名不能为空");
        }
        LoginVo loginVo = new LoginVo();
        try {
            Emp emp = empMapper.getEmpUsername(loginDto.getUsername());
            if (emp == null || !emp.getPassword().equals(loginDto.getPassword())) {
                throw new ClientException("用户名或密码错误");
            }
            loginVo.setId(emp.getId());
            loginVo.setName(emp.getName());
            loginVo.setUsername(emp.getUsername());
            loginVo.setToken(JWTkey.testEmpJWT(emp.getId(), emp.getName()));
        }catch (Exception e){
            throw new ClientException("用户名或密码错误");
        }
        return loginVo;
    }
}
